#! /usr/bin/python
# coding=utf-8

# 域名查询

import sys
import string
import socket

class domain_query:
  url_header = "www."

  whoiss = {
      "com": "whois.crsnic.net;whois.verisign-grs.com;whois.internic.com",
      "net": "whois.crsnic.netwhois.verisign-grs.com;whois.internic.com",
      "org": "whois.crsnic.net;whois.pir.org;whois.publicinterestregistry.net",
      "biz": "whois.networksolutions.com;whois.neulevel.biz",
      "info": "whois.networksolutions.com",
      "mil": "whois.networksolutions.com",
      "edu": "whois.educause.net",
      "cn": "whois.cnnic.net.cn"
      }

  def __init__( self ):
    self.domain = ""

  def __del__( self ):
    print "__del__"

  # 执行查询
  def query( self, url ):
    url = url.strip();
    url = url.lower()

    self.domain = url
    print "Query Domain:" + url

    # 检查是否是www.开头
    index = url.find( self.url_header )
    if index == 0:
      url = url[4:]

    # 获取whoise服务器
    whoise_server = self.get_whoise( url )

    # 连接服务器并查询
    query_ok = False
    whoise_list = whoise_server.split( ";" )
    for whoise in whoise_list:
      result = self.query_whoise( url, whoise )
      if result != -1:
        query_ok = True
        print "query from:" + whoise + " success"
        break;

    if query_ok == False:
      print "query domain failed"
      return -1;

    # 分析结果
    return result;

  # 根据域名后缀获取whoise服务器
  def get_whoise( self, url ):
    suffix = self.find_last_of( url, "." );
    return self.whoiss[suffix]

  # 从后向前查
  def find_last_of( self, source, finder ):
    splited = source.split( finder )
    return splited[len(splited)-1]

  # 从whoise服务器查询域名
  def query_whoise( self, url, whoise_server ):
    print "Query From Whoise Server:" + whoise_server
    try:
      sclient = socket.socket()
    except:
      return -1;
    try:
      sclient.connect( (whoise_server, 43) )
      sclient.send( url )
      sclient.send( "\r\n" )
      msg = sclient.recv( 1024 )
      while msg != "":
        if msg.find( "No match for" ) >= 0:
          sclient.close()
          return 0
        msg = sclient.recv( 1024 )
    except:
      sclient.close()
      return -1

    sclient.close()
    return 1

if __name__ == "__main__":
  qry = domain_query()
  result = qry.query( "www.baidu.com" )
  if result == 1:
    print "Domain [" + qry.domain + "] is registered"
  elif result == 0:
    print "Domain [" + qry.domain + "] is not registered"
  else:
    print "Query Failed"
